// 一. 导入express
const express = require('express')
// 二. 实例化router对象
const router = express.Router()

const { DEBUG } = require('../config/config_default')

// 导入db模块
const { getAll, getById, exec } = require('../db')
// 三. 编写路由规则

router.get('/', async (req, res) => {
	// 解析参数
	// console.log(req.query.keyword)
	const { page = 1, size = 10 } = req.query
	// 分页的公式:偏移量 = (页数-1)*每页显示数
	let offset = (page - 1) * size
	// 操作数据库
	let sql = `select count(*) as total from gg_event where event_type like '%${req.query.keyword}%' or event_addr like '%${req.query.keyword}%'`
	let { total } = await getById(sql)
	sql = `select *  from gg_event where event_type like '%${req.query.keyword}%' or event_addr like '%${req.query.keyword}%' limit ${offset},${size}`
	console.log(sql)

	try {
		// 正常的情况
		const resData = await getAll(sql)
		res.send({
			code: 0,
			message: '获取所有路况成功',
			result: { total: total, page, size, resData },
		})
	} catch (err) {
		// 异常的情况
		res.send({
			code: 100101,
			message: '获取所有路况失败',
			result: DEBUG ? err : '',
		})
	}
	// 返回结果
})

// 未使用
router.get('/:event_id', async (req, res) => {
	// 一. 解析id
	let { event_id } = req.params
	// 二. 操作数据库
	let sql = `select * from gg_event where event_id = ${event_id}`
	try {
		// 三. 返回结果
		var resData = await getById(sql)
	} catch (err) {
		res.send({
			code: 100103,
			message: '查询单个路况失败',
			result: DEBUG ? err : '',
		})
	}

	if (resData) {
		res.send({
			code: 0,
			message: '获取路况成功',
			result: resData,
		})
	} else {
		res.status(404).send({
			code: 100102,
			message: 'id对应的数据不存在',
			result: '',
		})
	}
})

router.post('/', async (req, res) => {
	// 解析参数(可以做参数格式的校验)

	const {
		report_user,
		event_type,
		event_addr,
		event_mark,
		event_time,
		event_describe,
	} = req.body
	if (!event_type) {
		return res.send({
			code: 100104,
			message: '参数格式不对',
			result: '',
		})
	}
	// 操作数据库
	let sql = `insert into gg_event (event_type,event_mark,event_addr,event_time,event_describe,report_user) values ('${event_type}','${event_mark}','${event_addr}','${event_time}','${event_describe}','${report_user}')`
	let { insertId } = await exec(sql)

	sql = `select * from gg_event where event_id=${insertId}`
	const resData = await getById(sql)
	// 返回结果
	res.send({
		code: 0,
		message: '添加成功',
		result: resData,
	})
})

router.put('/:id', async (req, res) => {
	// 解析参数
	let { event_id, event_status } = req.body

	// 操作数据库
	let sql = `update gg_event set event_status='${event_status}' where event_id=${event_id}`
	await exec(sql)
	res.send({
		code: 0,
		message: '更新成功',
		result: {
			event_id,
			event_status,
		},
	})
})

// 四. 导出router对象
module.exports = router
